<template>
  <div class="cost-adjustment-container">
    <BasicInformation
      title="添加成本调整"
      :primary-actions="actions"
      @action="handleAction"
    />

    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="120px"
    >
      <!-- 基础信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>

        <el-row :gutter="30">
          <el-col :md="12">
            <el-form-item label="编号" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入编号"
                clearable
                :disabled="true"
              />
            </el-form-item>
          </el-col>

          <el-col :md="12">
             <el-form-item label="单据日期" prop="date">
                      <el-date-picker
                        v-model="form.date"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledDate"
                      />
                    </el-form-item>
          </el-col>

          <el-col :md="12">
            <!-- 库管员 -->
                  <el-form-item label="库管员" prop="skid">

                    <el-select
                        v-model="form.skid"
                        placeholder="请选择库管员"
                        style="width: 240px"
                        clearable
                        filterable
                    >
                      <el-option
                          v-for="user in userList"
                          :key="user.id"
                          :label="`${user.name}`"
                          :value="user.id"
                      />
                    </el-select>

                  </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 商品清单 -->
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">商品清单</span>
            <el-button
              type="primary"
              size="small"
              @click="goodsDialogVisible = true"
            >
              添加商品
            </el-button>
          </div>
        </template>

        <el-table
          :data="form.goods"
          border
          style="width: 100%"
        >
          <el-table-column prop="code" label="商品编码" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="kname" label="商品分类" />
          <el-table-column prop="uname" label="商品单位" />
          <el-table-column prop="tax" label="税率" />
          <el-table-column label="调整金额">
            <template #default="{ row, $index }">
              <el-input-number v-model="form.counts[$index]" :step="0.01" />
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 商品选择对话框 -->
      <MaterialSelectorDialog
        v-model:modelValue="form.goods"
        v-model:visible="goodsDialogVisible"
      />

    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { CostAdjustment, Good } from '@/types/kc/CBTZ'
import BasicInformation from '@/public-view/BasicInformation.vue'
import MaterialSelectorDialog from '@/basic-view/bom/MaterialSelectorDialog.vue'
import axios from 'axios'
import type {User} from "@/types/rs/User.ts";
import request from '@/util/request'

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

// 表单数据：不含 status，后端默认设为1
const form = reactive<Partial<CostAdjustment>>({
  id: 0,
  code: '',
  date: new Date,
  skid: 0,
  goods: [] as Good[],
  counts: [] as number[],
  delFlag: 0,
  typeId :7,
  createUser: user.user.name,
  updateUser: user.user.name,
})

const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
}

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

// 验证规则：code、date、skid 必填
const rules = reactive<FormRules>({
  code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  skid: [{ required: true, message: '请输入 Skid', trigger: 'blur' }]
})

// 弹窗控制
const goodsDialogVisible = ref(false)

// 操作按钮
const actions = [
  { name: 'save', label: '保存', type: 'primary' },
  { name: 'reset', label: '重置', type: 'warning' }
]

// 表单引用
const formRef = ref<FormInstance>()

// goods 改变时重置 counts
watch(
  () => form.goods,
  goods => { form.counts = goods?.map(() => 0) || [] },
  { deep: true }
)

// 处理操作
function handleAction(action: string) {
  action === 'save' ? submitForm() : resetForm()
}

async function submitForm() {
  try {
    await formRef.value?.validate()

    const payload = JSON.parse(JSON.stringify({
      ...form,
      goods: form.goods,
      counts: form.counts
    }))

    console.log('发送 BOM 数据（深拷贝后）:', payload)

    const resp = await request.post(
      'kc/proChange/add',
      payload,
      {
        headers: {
          "Content-Type": "application/json"
        }
      }
    )

    if (resp.data.code === '200' || resp.data.code === 200) {
      ElMessage.success(resp.data.message || '添加成功')
    } else {
      ElMessage.error(resp.data.message || '添加失败')
    }
  } catch (err: any) {
    console.error('提交失败：', err)
    ElMessage.error('网络或服务异常，保存失败')
  }
}

//访问方法并获取单据编号
let getDocCode=async()=>{
  let response=await request.post('xs/counter/addCode',{docType:'CBTZ'})
  console.log(response.data.data)
  form.code=response.data.data
}
getDocCode()


// 重置表单
function resetForm() {
  formRef.value?.resetFields()
  form.goods = []
  form.counts = []
  ElMessage.info('已重置表单')
}
</script>

<style scoped>
.cost-adjustment-container { padding: 20px; }
.form-section { margin-bottom: 20px; }
.section-header { display: flex; justify-content: space-between; align-items: center; }
.section-title { font-size: 16px; font-weight: 600; }
</style>
